#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int DumpAll(char* szRomName, char* szFolder);
int InsertAll(char* szRomName, char* szFolder);

int main(int argc, char* argv[])
{

	if(argc < 3)
	{
		printf("USO: CTTileMap -[d|i] <rom> <pasta>.\n\n");
		return 0;
	}

	if(!strcmp(argv[1], "-d"))
		DumpAll(argv[2], argv[3]);
	else if(!strcmp(argv[1], "-i"))
		InsertAll(argv[2], argv[3]);
	else
		printf("Opcao invalida.\n\n");

	
	
	return 0;
}

int DumpAll(char* szRomName, char* szFolder)
{

	printf("***Dumpando Mapas de Tiles -> ");
	//
	//
	FILE* fpRom;
	if(!(fpRom = fopen(szRomName, "rb")))
	{
		printf("ERRO.\n");
		exit(-1);
	}

	FILE* fpOut;
	
	fseek(fpRom, 0x308200, SEEK_SET);
	for(int z = 0; z < 6; z++)
	{
		char Name[40];
		sprintf(Name, "%s/TM-%02X.txt",szFolder, z);
		if(!(fpOut = fopen(Name, "wb")))
		{
			printf("ERRO.\n");
			exit(-1);
		}

		
		for(int x = 0; x < 0x20; x++)
		{
			for(int y = 0; y < 0x20; y++)
			{
				int iBuffer = getc(fpRom) | (getc(fpRom)<<8);
				fprintf(fpOut, "%03X ", iBuffer);
			}
			putc('\n', fpOut);
		}

		fclose(fpOut);
	}
	

	//
	//
	fclose(fpRom);

	printf("Pronto.\n");
	return 0;
}

int InsertAll(char* szRomName, char* szFolder)
{

	printf("***Inserindo Mapas de Tiles -> ");
	//
	//
	FILE* fpRom;
	if(!(fpRom = fopen(szRomName, "r+b")))
	{
		printf("ERRO ao abrir a rom \'%s\'.\n", szRomName);
		exit(-1);
	}

	FILE* fpOut;
	
	fseek(fpRom, 0x308200, SEEK_SET);
	for(int z = 0; z < 6; z++)
	{
		char Name[40];
		sprintf(Name, "%s/TM-%02X.txt",szFolder, z);
		if(!(fpOut = fopen(Name, "rb")))
		{
			printf("ERRO ao abrir o mapa\'%s\'.\n", Name);
			exit(-1);
		}

		int iBuffer;
		while(!feof(fpOut))
		{
			fscanf(fpOut, "%03X ", &iBuffer);
			
			putc(iBuffer & 0xFF, fpRom);
			putc(iBuffer >> 8, fpRom);

		}
		fclose(fpOut);
	}
	

	//
	//
	fclose(fpRom);

	printf("Pronto.\n");
	return 0;
}
